package utils;

import java.util.*;

public class HttpQueue {
	private final static int MAX_ITEM = 10;
	private Vector<HttpItem> items = null;
	private HttpHandler myHandler = null;
	
	public HttpQueue() {
		items = new Vector<HttpItem>();
		myHandler = new HttpHandler(this);
	}
		
	public synchronized HttpItem get(String url, HttpItemListener listener, Object param, boolean bxml) {
		HttpItem item = new HttpItem();
		item.bxml = bxml;
		item.requestUrl = url;
		item.listener = listener;
		item.param = param;
		insertItem(item);
		return item;
	}
	
	public synchronized HttpItem post(String url, Dictionary<String, Object> form, boolean bMultipary, HttpItemListener listener, Object param, boolean bxml) {
		HttpItem item = new HttpItem();
		item.bxml = bxml;
		item.requestUrl = url;
		item.formData = form;
		item.listener = listener;
		item.param = param;
		item.bMultipary = bMultipary;
		item.bPost = true;
		insertItem(item);
		return item;
	}
	
	private void insertItem(HttpItem item) {
		if (items.size() < MAX_ITEM) {
			item.httpHandler = myHandler;
			Thread t = new Thread(item);
			t.start();
		}
		items.addElement(item);
	}
	
	public synchronized void httpCallback(HttpItem item, boolean successfull) {
		items.removeElement(item);
		if (item.listener != null) {
			item.listener.reqeuestFinished(item.byteArray, item.xml, successfull, item.param);
		}
		item.listener = null;
		item.xml = null;
		item.byteArray = null;
		item.param = null;
		item.formData = null;
		for (int i = 0; i < items.size(); i++) {
			item = (HttpItem) items.elementAt(i);
			if (i < MAX_ITEM) {
				if (item.httpHandler == null) {
					item.httpHandler = myHandler;
					Thread t = new Thread(item);
					t.start();
				}
			}
		}
	}
	
	public synchronized void cancel(HttpItem item) {
		int index = items.indexOf(item);
		if (index >= 0 && index < MAX_ITEM) {
			item.cancel();
			items.removeElement(item);
			for (int i = 0; i < items.size(); i++) {
				item = (HttpItem) items.elementAt(i);
				if (i < MAX_ITEM) {
					if (item.httpHandler == null) {
						item.httpHandler = myHandler;
						Thread t = new Thread(item);
						t.start();
					}
				}
			}
		} else {
			items.removeElement(item);
		}
	}
}
